<?php
class Order_Service_OrderReProccess
{
	protected $_order = null;	 
	protected $_orderCode = null;
	protected $_plan = null;
	protected $_customerId = null;
	protected $_procCnt  = null;
	protected $_products = null;
	protected $_chargeBalance = 0;//扣取费用
	protected $_isDispatch = false;//是否有分开（套餐/Balance）扣取
	protected $_chargeBalanceCurrency = null;
	protected $_outOfStock = false;
	protected $_outOfBalance = false;
	protected $_error = null;
	protected $_warning = null;
	 
	protected $_volume = null;
	protected $_weight = null;
	protected $_shipFee = null;
	protected $_shipFeeCurrencyCode = null;
	protected $_status = null;
	protected $_checkOutOfPlan = false;
	protected $_customerPlan = null;
	protected $_feeEnforce = false;//强制扣款
	protected $_gwem = false;//注册在一个月内
	protected $_msg = "";//订单处理结果信息
	
	public function __construct($orderCode){	
		 if(isset($orderCode)){
			$this->_orderCode = $orderCode;
			$this->setOrder();
		}
	}
	
	/**
	* 用户分发订单
	* @param orderCode
	* @return array|boolean success return boolean,false return array
	*/
	 public function submited($orderCode=null,$status,$isCheckPlan=false,$feeEnforce=false){
		
		//init Transaction
		$customerBalance = new Customer_Model_CustomerBalance();
		$dbAdapter = $customerBalance->getAdapter();		 
		$dbAdapter->beginTransaction();
		//事务  保证数据从主数据库取得
		if(isset($orderCode)){
			$this->_orderCode = $orderCode;
			$this->setOrder();
		}
		$this->setCustomer();
		$this->_feeEnforce = $feeEnforce;
		
		if($this->_order['orders_status']!=4){
			$this->_msg =  array('ask'=>'Error','err_type'=>'status','orders_code'=>$this->_orderCode,'msg'=>"status err, orders_status is not 4");
			return 	$this->_msg;
		}
		
		$this->_status = $status;	
				 				
		try{	
			$this->vaildateOrder();
			if(!empty($this->_error)){
				$dbAdapter->rollback();
				$this->_msg = array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>$this->_error);	
				return 	$this->_msg;
			}
			
			$this->picking();
								
			if($this->_outOfStock){
				$dbAdapter->rollback();
				$this->_msg =  array('ask'=>'Error','err_type'=>'stock','orders_code'=>$this->_orderCode,'msg'=>$this->_error);	
				
				return 	$this->_msg;	
			}
							
			$this->shippingFee();

			$this->holdShippingFee();
			if($this->_outOfBalance==true){
				$dbAdapter->rollback();	
				$this->_msg =  array('ask'=>'Error','err_type'=>'balance','orders_code'=>$this->_orderCode,'msg'=>$this->_error);
				
				return 	$this->_msg;		
			}		
		}catch(Exception $e){
			$dbAdapter->rollback();
			$this->_msg =  array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>'Internal Error1');	
			return 	$this->_msg;		
		}
				
		$this->_msg =  array('ask'=>'Success','orders_code'=>$this->_orderCode,'msg'=>'resubmit Success,orders_status from 4 to 3,process_status from 0 to 1');
		if(!$this->update()){
			$dbAdapter->rollback();	
			$this->_msg =  array('ask'=>'Error','orders_code'=>$this->_orderCode,'msg'=>'Internal Error2');	
			return 	$this->_msg;		
		}
		$dbAdapter->commit();
		
		return 	$this->_msg;	
	 }	 
	 /*
	 *
	 *获取客户LOGIN信息
	 *
	 */
	 public function setCustomer($customerId=null){	
		$this->_customerId = $this->_order['customer_id'];
	 }
	/**
	*注册日期在一个月内
	*/
	 private function getByCustomerIdGwem(){
		$CustomerModel= new Merchant_Model_Customer();
		$cRow=$CustomerModel->getByGwemCustomerId($this->_customerId);
		if(!empty($cRow)){
			$this->_gwem=true;
		}
	 }
	
	 /*
	 *
	 *下架处理
	 *
	 */	 
	 private function picking(){
		$itemCnt = 0;
		foreach ($this->_products as $val){
			$warehouseId = 1;
			if(!Product_Service_ProductStocket::pickingProcdut($val['product_id'],$val['op_quantity'],$warehouseId,"orders_code:".$this->_orderCode)){
				$this->_outOfStock = true;
				$this->_error = $val['product_sku']. " available stock is not sufficient for this order.";
				break;
			}
			$pdObj = new Product_Service_Product();
			$productRow = $pdObj->getByProductId($val['product_id']);
			$this->_volume += $productRow['product_length']*$productRow['product_width']*$productRow['product_height'];
			$this->_weight += $productRow['product_weight'];
			$itemCnt += $val['op_quantity'];
			$this->_procCnt = $itemCnt;
		}
	 }

	 //TODO validate 物流验证//
	 private function vaildateOrder(){
// 		$this->_error = Merchant_Service_FactoryValidate::factoryMethod($this->_order); 
	 }
	 
	 /*
	 *
	 *Calc shipping fee
	 */
	 private function shippingFee(){
		$shipMethod = Shipping_Service_ShipType::getByValue($this->_order['shipping_method'],'st_code');
 	
		$options = array('warehouseId'=>1,
						'countryId'=>$this->_order['consignee_country_id'],	
						'stId'=>$shipMethod['st_id'],
						'weight'=>$this->_weight,
						'length'=>1,
						'width'=>1,
						'height'=>$this->_volume,
						'customerId'=>$this->_customerId
						);
		$shipFeeObj = new Shipping_Service_ShipFeeCalc($options);		
		
		$fee = $shipFeeObj->calcFeeByType();
//		print_r($fee);exit;
		$this->_shipFee = $fee['inter_fee'];
		$this->_shipFeeCurrencyCode =  $fee['currency_code'];//TODO 更改运费计算，返回加上货币种类 
	 }
	 
	 
	 /*
	* hold fee
	*
	*/
	 private function holdShippingFee(){
		$note = 'Withdrawal shipping fee '.$this->_shipFee.'. Order:'.$this->_order['orders_code'];
		$options = array('cbhClass'=>1,	//正常扣款
							 'refCode'=>$this->_order['orders_code'],
							 'appType'=>6,	//物流费用
							 'cbhType'=>'-1',
							 'vale'=>$this->_shipFee,
							 'currencyCode'=>$this->_shipFeeCurrencyCode,
							 'note'=>$note
							);
		$ress = Customer_Service_CustomerBalance::procBalance($this->_customerId,$options);
//		print_r($options);exit;
 	
		if(!$ress){
			$this->_error  = 'Out of balance, please deposit you Cff account.';
			$this->_outOfBalance = true;
			return false;
		}
		return true;
	 }
	 
	 /*
	 *Update orders
	 *
	 */
	 
	 private function update(){
		$Obj = new Order_Model_Order();
		$updateRow = array("orders_status"=>$this->_status);
		if($this->_status=='3'){
			$updateRow['process_status'] = 1;
			$updateRow['underreview_status'] = 0;
			$updateRow['submit_time'] = date('Y-m-d H:i:s');
		}
		if($this->_outOfStock){
			$updateRow = array(
				"orders_status"=>4,
				"underreview_status" => 1
			);			
			$updateRow['process_status'] = 0;
		}
		if($this->_outOfBalance){
			$updateRow = array(
				"orders_status"=>4,
				"underreview_status" => 2
			);
			$updateRow['process_status'] = 0;
		}
		if($Obj->update($updateRow,$this->_order['order_id'])){
			$this->writeLog();
			return true;
		}
		return false;
	 }
	 
	 private function setOrder(){
		if(!isset($this->_order)||$this->_order['orders_code']==$this->_orderCode ){		 
			$this->_order = Order_Service_Order::getByOrdersCode($this->_orderCode);			 
			$condition['orders_code'] = $this->_orderCode;
			$this->_products = Order_Service_Product::getByCondition($condition);
			$this->_order['order_product'] = $this->_products;
		}
	 }
	 /*
	 *
	 *Return Order Info
	 */
	 public function getOrder(){
		 return $this->_order;
	 } 
	 
	 public function writeLog(){
		if(!empty($_SERVER['REMOTE_ADDR'])){
			$ip=$_SERVER['REMOTE_ADDR'];
		}else{
			$ip=gethostbyname($_SERVER["SERVER_NAME"]);
		}
		$logRow = array(
			"orders_code" => $this->_orderCode,
			"osh_type" => "General",
			"osh_statu" => $this->_status,
			"osh_create_date" => date("Y-m-d H:i:s"),
			"osh_comments" => $this->_msg['msg'],
			"osh_remark" => "",
			"user_id" => -1,
			"osh_ip" => $ip,
		);
		if($this->_outOfStock){
			$logRow["osh_statu"] = 4;
			$logRow["osh_comments"] =  is_array($this->_error)?(implode("|", $this->_error)):$this->_error;
		}
		if($this->_outOfBalance){
			$logRow["osh_statu"] = 4;
			$logRow["osh_comments"] = "out of balance";
		}
		$model = new Order_Model_History();
		$model->create($logRow);
	 }	 
	 
}